package com.bbbk.util.word.conf.globalexception.conf;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;


public class HandlerExceptionResolverImpl extends AbstractHandlerExceptionResolver {
	private final static Logger log = LoggerFactory.getLogger(HandlerExceptionResolverImpl.class);
	
	public int getOrder() {
	    return 0;
	}
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		log.error("全局异常处理开始");
		log.error("{}",ex);
		log.error("{}",ex.getMessage());
		
		
		return warp("500", ex.getMessage(), ex);
		
	}
	/**
	 * 默认500
	 */
//	private String getCode(Exception ex) {
//		String errCode = "500";
//		Class<? extends Exception> class1 = ex.getClass();
//		Method method = null;
//		try {
//			method = class1.getMethod("getCode");
//		} catch (Exception e) {
//		}
//		
//		try {
//			if(method == null)
//			method = class1.getDeclaredMethod("getCode");
//		} catch (Exception e) {
//		}
//		if(method!=null) {
//			try {
//				Object invoke = method.invoke(ex);
//				if(invoke!=null) {
//					String code = invoke.toString();
//					if(!StrUtil.isEmpty(code)) {
//						errCode = code;
//					}else {
//						log.error("异常信息code为空");
//					}
//				}
//			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
//				log.error("无法执行getCode, {}",class1.getName());
//			}
//		}
//		
//		return errCode;
//	}
	private ModelAndView warp(String code,String message,Exception ex) {
		ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("resultStatus",  code);
        attributes.put("msg",  message);
        view.setAttributesMap(attributes);
        mv.setView(view);
        ex.printStackTrace();
        return mv;
	}

}

